package com.tehui.activity.impl;

import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.WindowManager;
import android.widget.EditText;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.tehui.R;
import com.tehui.activity.BaseActivity;
import com.tehui.adapter.GridImageAdapter;
import com.tehui.utils.tools.PrefUtils;
import com.tehui.utils.ui.FullyGridLayoutManager;
import com.tehui.utils.ui.UiUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

import static com.luck.picture.lib.config.PictureConfig.LUBAN_COMPRESS_MODE;

//意见反馈
public class OpinionActivity extends BaseActivity {

    @BindView(R.id.rl)
    RecyclerView rl;
    @BindView(R.id.editText)
    EditText     editText;
    @BindView(R.id.contact)
    EditText     contact;

    private String nick;
    private List<LocalMedia> selectList = new ArrayList<>();
    private ArrayList<File>  files;
    private String           s;
    private GridImageAdapter adapter;

    @Override
    public void initActivityData() {
        super.initActivityData();
        tvTitle.setText("意见反馈");
        nick = PrefUtils.getString("nick", "");
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        files = new ArrayList<>();
        initWidget();
    }

    private void initWidget() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(OpinionActivity.this, 4,
                GridLayoutManager.VERTICAL, false);
        rl.setLayoutManager(manager);
        adapter = new GridImageAdapter(OpinionActivity.this, onAddPicClickListener);
        rl.setAdapter(adapter);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_opinion;
    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter
            .onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            // 进入相册 ：不需要的api可以不写
            PictureSelector.create(OpinionActivity.this).openGallery(PictureMimeType.ofImage())// 全部
                    //.theme(themeId)// 主题样式设置 具体参考 values/styles
                    .maxSelectNum(4)// 最大图片选择数量
                    .minSelectNum(0)// 最小选择数量
                    .imageSpanCount(4)// 每行显示个数
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                    .previewImage(true)// 是否可预览图片
                    .compressGrade(Luban.THIRD_GEAR)// luban压缩档次，默认3档 Luban.FIRST_GEAR、Luban.CUSTOM_GEAR
                    .isCamera(false)// 是否显示拍照按钮
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    .compress(true)// 是否压缩
                    .compressMode(LUBAN_COMPRESS_MODE)//系统自带 or 鲁班压缩 PictureConfig.SYSTEM_COMPRESS_MODE or
                    .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                    .isGif(false)// 是否显示gif图片
                    .openClickSound(false)// 是否开启点击声音
                    //.selectionMedia(selectList)// 是否传入已选图片
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回两种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    addFile();
                    break;
            }
        }
    }

    private void addFile() {
        for (LocalMedia localMedia : selectList) {
            files.add(new File(localMedia.getCompressPath()));
        }
    }

    @OnClick(R.id.submit)
    public void onClick() {
        sendMessage();
    }

    private void sendMessage() {
        String contacts = contact.getText().toString().trim();
        String message = editText.getText().toString().trim();
        String versionName = UiUtils.getVersionName();
        if (TextUtils.isEmpty(message)) {
            UiUtils.toast("请输入您的问题!");
            return;
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("Message", message);
            jsonObject.put("nick", nick);
            jsonObject.put("versionName", versionName);
            if (!TextUtils.isEmpty(contacts)) {
                jsonObject.put("Contact", contacts);
            }
            s = jsonObject.toString();

        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (files != null) {
            OkGo.post("http://dl.21tehui.com/AppFeedbackApi/test.html").tag(this).params("word", s)
                    .addFileParams("image[]", files).cacheKey("cacheKey").cacheMode(CacheMode.DEFAULT)
                    .execute(new StringCallback() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    if (s.equals("1")) {
                        UiUtils.toast("上传成功");
                        editText.setText("");
                        contact.setText("");
                        deletePic();
                    } else if (s.equals("2")) {
                        UiUtils.toast("上传失败");
                    }
                }
            });

        } else {
            OkGo.post("http://dl.21tehui.com/AppFeedbackApi.html").tag(this).params("word", s).cacheKey
                    ("cacheKey").cacheMode(CacheMode.DEFAULT).execute(new StringCallback() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    if (s.equals("1")) {
                        UiUtils.toast("上传成功");
                        editText.setText("");
                        contact.setText("");
                    } else if (s.equals("2")) {
                        UiUtils.toast("上传失败");
                    }
                }
            });
        }
    }

    private void deletePic() {
        PictureFileUtils.deleteCacheDirFile(OpinionActivity.this);
        files.clear();
        selectList.clear();
        adapter.notifyDataSetChanged();
    }
}
